package test_bitmap;

import org.junit.Test;
import org.roaringbitmap.RoaringBitmap;

import java.io.*;
import java.sql.*;

public class RoaringBitmapTest {

    @Test
    public  void test1() {
        RoaringBitmap btm = RoaringBitmap.bitmapOf(1, 5, 8);
        System.out.println(btm.contains(8));
        System.out.println(btm.contains(9));
        System.out.println(btm.contains(1));
        btm.add(9);
        System.out.println(btm.contains(9));
    }

    /**
     * 这里演示的是web开发组做的工作
     * @throws IOException
     * @throws SQLException
     */
    @Test
    public void test2() throws IOException, SQLException {
        // 根据规则参数静态画像条件，去画像库中查询满足条件的人群id列表
        RoaringBitmap btm = RoaringBitmap.bitmapOf(1, 5, 8,12);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);

        // 序列化
        btm.serialize(dout);
        byte[] btmBytes = bout.toByteArray();

        // 插入数据库
        Connection conn = DriverManager.getConnection("jdbc:mysql://doitedu:3306/doit35", "root", "root");
        PreparedStatement stmt = conn.prepareStatement("insert into test_btm values(?)");
        stmt.setBytes(1,btmBytes);

        stmt.execute();

        stmt.close();
        conn.close();
    }

    /**
     * 演示flink端要做的事情
     */
    @Test
    public void test3() throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://doitedu:3306/doit35", "root", "root");
        PreparedStatement stmt = conn.prepareStatement("select btm_bytes from test_btm ");
        ResultSet resultSet = stmt.executeQuery();
        resultSet.next();
        byte[] btmBytes = resultSet.getBytes(1);

        stmt.close();
        conn.close();

        // 反序列化
        RoaringBitmap btm = RoaringBitmap.bitmapOf();

        ByteArrayInputStream bIn = new ByteArrayInputStream(btmBytes);
        DataInputStream dataIn = new DataInputStream(bIn);

        btm.deserialize(dataIn);

        // 测试可用否
        System.out.println(btm.contains(1));
        System.out.println(btm.contains(5));
        System.out.println(btm.contains(8));
        System.out.println(btm.contains(12));
        System.out.println(btm.contains(22));
        System.out.println(btm.contains(32));


    }



}
